//
//  NCFilterTableView.swift
//  FilterBox
//
//  Created by 张文晏 on 2018/11/7.
//  Copyright © 2018 张文晏. All rights reserved.
//

import UIKit

public class NCFilterTableView: UIView, NCFilterTable {
    public var filterBox: NCFilterBox?
    
    public var filterTabButton: NCFilterTabButton?
    
    public var isMultiSelection: Bool = false
    
    @IBOutlet public weak var tableView: UITableView!
    
    @IBOutlet weak var contentView: UIView!
    @IBOutlet weak var btnStartTime: UIButton!
    @IBOutlet weak var btnEndTime: UIButton!
    @IBOutlet var bottomView: NCFilterBottomView!
    
    @IBOutlet weak var constraintTableViewHeight: NSLayoutConstraint!
    @IBOutlet weak var constraintTimeViewHeight: NSLayoutConstraint!
    @IBOutlet weak var constraintBottomViewHeight: NSLayoutConstraint!
    @IBOutlet public weak var constraintContentViewTop: NSLayoutConstraint!
    
    @IBAction func clickBg(_ sender: Any) {
        hide()
    }
    
    @IBAction func editStartTime(_ sender: Any) {
        selectedItems.removeAll()
        tableView.reloadData()
        selectedDateClosure?(date)
    }
    
    @IBAction func editEndTime(_ sender: Any) {
        selectedItems.removeAll()
        tableView.reloadData()
        selectedDateClosure?(date)
    }
    
    
    func reset() {
        selectedItems.removeAll()
        btnStartTime.setTitle("开始时间", for: .normal)
        btnEndTime.setTitle("结束时间", for: .normal)
        date = nil
        tableView.reloadData()
    }
    
    func confirm() {
        hide()
        if date != nil{
            let title = date!.0.string(withFormat: "yyyy-MM-dd") + "至" + date!.1.string(withFormat: "yyyy-MM-dd")
            filterTabButton?.set(name: title, selected: true)
        }else{
            if isMultiSelection || selectedItems.isEmpty{
                filterTabButton?.set(name: filterTabButton!.originalTitle, selected: false)
            }
        }
        selectedClosure?(selectedItems, date)
    }
    
    lazy var searchHeader = NCFilterBoxSearchHeaderView.init(frame: CGRect.init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 44))
    
    private var items = [NCFilterBox.IdNameItem]()
    public var selectedItems = [NCFilterBox.IdNameItem]()
    
    public var selectedClosure:((_ items:[NCFilterBox.IdNameItem], _ date:(Date, Date)?)->())?
    public var selectedDateClosure: ((_ date: (Date, Date)?)->())?
    public var hideClosure:(()->())?
    
    public var isShowTimeView = false{
        didSet{
            constraintTimeViewHeight.constant = isShowTimeView ? 44 : 0
        }
    }
    
    public var isShowBottomView = false{
        didSet{
            constraintBottomViewHeight.constant = isShowBottomView ? 54 : 0
        }
    }
    
    public var isShowSearchHeader = false{
        didSet{
            if isShowSearchHeader{
                tableView.tableHeaderView = searchHeader
            }
        }
    }
    
    var date: (Date, Date)?
    var positionY: CGFloat = 44
    
    public init(positionY: CGFloat? = 44) {
        super.init(frame: CGRect.init(x: 0, y: positionY ?? 44, width: UIScreen.main.bounds.width, height: 600))
        _ = fromNib()
        self.positionY = positionY ?? 44
        bottomView.resetClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reset()
        }
        bottomView.confirmClosure = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.confirm()
        }
        let bundle = Bundle.init(for: self.classForCoder)
        tableView.register(UINib.init(nibName: "NCFilterTableViewCell", bundle: bundle), forCellReuseIdentifier: "NCFilterTableViewCell")
        tableView.delegate = self
        tableView.dataSource = self
        
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    public func set(items: [NCFilterBox.IdNameItem]){
        self.items = items
        tableView.reloadData()
    }
    
    public func add(items: [NCFilterBox.IdNameItem]){
        self.items.append(contentsOf: items)
        tableView.reloadData()
    }
    
    public func search(_ searchClosure: ((_ text: String?)->())?){
        searchHeader.searchClosure = searchClosure
    }
    
    public func set(startDate: Date, endDate: Date){
        btnStartTime.setTitle(startDate.string(withFormat: "yyyy-MM-dd"), for: .normal)
        btnEndTime.setTitle(endDate.string(withFormat: "yyyy-MM-dd"), for: .normal)
        date = (startDate, endDate)
    }
    
    public func show(){
        if let box = filterBox, let owner = box.owner{
            owner.view.insertSubview(self, belowSubview: box.tabButtonContainer)
            self.frame = CGRect.init(x: 0, y: positionY, width: owner.view.bounds.width, height: owner.view.bounds.height - positionY)
        }
        updateUI()
    
        constraintContentViewTop.constant = -contentView.bounds.height
        layoutIfNeeded()
        constraintContentViewTop.constant = 0
        UIView.animate(withDuration: 0.3) {
            self.layoutIfNeeded()
        }
    }
    
    public func hide(){
        hideClosure?()
        filterTabButton?.isSelected = false
        constraintContentViewTop.constant = -contentView.bounds.height
        UIView.animate(withDuration: 0.3, animations: {
            self.layoutIfNeeded()
        }) { (_) in
            self.removeFromSuperview()
        }
        
    }
    
    func updateUI(){
        tableView.reloadData()
        setNeedsLayout()
        layoutIfNeeded()
        let height = tableView.contentSize.height
        constraintTableViewHeight.constant = min(height, 300)
    }
    
}

extension NCFilterTableView: UITableViewDelegate, UITableViewDataSource{
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "NCFilterTableViewCell", for: indexPath) as! NCFilterTableViewCell
        let item = items[indexPath.row]
        cell.title = item.name
        cell.isMultiSelection = isMultiSelection
        cell.beSelected = selectedItems.contains(where: {$0.name == item.name})
        return cell
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedItem = items[indexPath.row]
        btnStartTime.setTitle("开始时间", for: .normal)
        btnEndTime.setTitle("结束时间", for: .normal)
        date = nil
        if isMultiSelection{
            if let idx =  selectedItems.index(where: {$0.id == selectedItem.id}){
                selectedItems.remove(at: idx)
            }else{
                selectedItems.append(selectedItem)
            }
            tableView.reloadRows(at: [indexPath], with: .fade)
        }else{
            selectedItems = [selectedItem]
            if indexPath.row == 0 && selectedItem.name == "全部" {
                filterTabButton?.set(name: filterTabButton!.originalTitle, selected: false)
            }else{
                filterTabButton?.set(name: selectedItem.name, selected: true)
            }
            if !isShowBottomView{
                selectedClosure?(selectedItems, nil)
                hide()
            }
            tableView.reloadData()
        }
    }
    
}
